<?php

declare(strict_types=1);

namespace App\Service\Business;

use App\Service\Access\RoleAccess;
use Hyperf\Di\Annotation\Inject;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;

/**
 * 角色-业务类
 */
class RoleBusiness extends BaseBusiness
{
        #[Inject]
        protected RoleAccess $RoleAccess;

        /**
         * 创建
         * @return array
         * @throws ContainerExceptionInterface
         * @throws NotFoundExceptionInterface
         */
        public function create(): array
        {
                $arrInsert = [
                        'roleSnowflakeId' => snowflakeId(),
                        'name' => $this->request->input('name'),
                        'status' => $this->request->input('status'),
                        'sort' => $this->request->input('sort', DEFAULT_SORT),
                        'createTime' => $this->request->getAttribute('timestamp'),
                ];
                $intRoleId = $this->RoleAccess->insertGetId($arrInsert);
                if (!$intRoleId) return businessError();
                $this->createOperateLog([], $arrInsert);
                return businessSuccess(['roleId' => $intRoleId]);
        }

        /**
         * 更新
         * @return array
         * @throws ContainerExceptionInterface
         * @throws NotFoundExceptionInterface
         */
        public function update(): array
        {
                $arrData = $this->RoleAccess->find($this->request->input('roleId'), ['name', 'status', 'sort', 'updateTime']);
                $arrUpdate = [
                        'roleId' => $this->request->input('roleId'),
                        'name' => $this->request->input('name'),
                        'status' => $this->request->input('status'),
                        'sort' => $this->request->input('sort', DEFAULT_SORT),
                        'updateTime' => $this->request->getAttribute('timestamp'),
                ];
                $intEffectRow = $this->RoleAccess->updateById($arrUpdate);
                if (!$intEffectRow) return businessError();
                $this->createOperateLog($arrData, $arrUpdate);
                return businessSuccess();
        }

        /**
         * 分页
         * @param array $inject
         * @return array
         */
        public function paginate(array $inject = []): array
        {
                $arrQueryResult = $this->RoleAccess->paginate($inject);
                $arrResult = [
                        'page' => $arrQueryResult['current_page'],
                        'limit' => $arrQueryResult['per_page'],
                        'total' => $arrQueryResult['total'],
                        'list' => $arrQueryResult['data'],
                ];
                return businessSuccess($arrResult);
        }
}